package com.lhlk.初始化;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 反射方式 和 普通方式 以及 反射方式关闭检测
 */
public class 性能测试 {
    //普通方式
    public static void test1(){
        User user=new User();
        long startTime=System.currentTimeMillis();
        for (int i = 0; i < 1000000000; i++) {
            user.getAge();
        }
        long endTime=System.currentTimeMillis();
        System.out.println("普通方式用时"+(endTime-startTime));
    }

    //反射方式
    public static void test2(){
        try {
            User user=new User();
            Class aClass = user.getClass();
            Method getAge = aClass.getDeclaredMethod("getAge", null);
            long startTime=System.currentTimeMillis();
            for (int i = 0; i < 1000000000; i++) {
                getAge.invoke(user,null);
            }
            long endTime=System.currentTimeMillis();
            System.out.println("反射方式用时"+(endTime-startTime));
        }catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    //反射方式，关闭检测
    public static void test3(){
        try {
            User user=new User();
               Class aClass = user.getClass();
            Method getAge = aClass.getDeclaredMethod("getAge", null);

            getAge.setAccessible(true);

            long startTime=System.currentTimeMillis();

            for (int i = 0; i < 1000000000; i++) {
                getAge.invoke(user,null);
            }

            long endTime=System.currentTimeMillis();
            System.out.println("关闭检测用时"+(endTime-startTime));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }  catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }
}
